#include "Protocol.hpp"
#include "Socket.hpp"
#include <unistd.h>
using namespace Protocal;
int main(int argc, char **argv)
{
    if (argc != 3)
    {
        std::cout << "Usage: " << argv[0] << "ip port" << std::endl;
        return 0;
    }
    std::string severip = argv[1];
    uint16_t severport = std::stoi(argv[2]);

    network::TcpSocket *s = new network::TcpSocket();
    if (!s->BuildClientSocketMethod(severip, severport))
    {
        std::cerr << "connect" << severip << ":" << severport << "fail" << std::endl;
    }
    else
        std::cout << "connet " << severip << ":" << severport << " success " << s->GetSockfd() << std::endl;

    // std::string message = "hello world";
    std::unique_ptr<Factory> factory = std::make_unique<Factory>();
    std::shared_ptr<Request> req = factory->BuildRequest(10, 20, '+');
    std::string resposestr;
    // write(s->GetSockfd(),message.c_str(),message.size());
    while (true)
    {
        std::string Requeststr;
        req->Serialize(&Requeststr);
       // std::cout <<"Serilize sucess" <<std::endl;
        Requeststr = Encode(Requeststr);
        //std::cout <<"Encode sucess" <<std::endl;
        // 发送请求
        s->Send(Requeststr);
        //std::cout <<"send sucess" <<std::endl;
        // 读取响应
        std::string resposestr;
        while (true)
        {
            if(!s->Recv(&resposestr, 1024))
            {
            //    std::cout <<"recv sucess" <<std::endl;
                break;
            }
            //std::cout <<"recv sucess" <<std::endl;
            // 解析
            std::string response;
            if (!Decode(resposestr, &response))
                continue;

            // 对请求反序列化

            auto resp = factory->BuildRespose();
            resp->deSerialize(response);
            std::cout << resp->GetResult() << std::endl;
            break;
        }
        sleep(1);
    }
    s->CloseSockfd();
    // sleep(10);
    return 0;
}